import React, { useState, useEffect, useCallback } from 'react';
import { Table, Card, DatePicker, Space, message, Row, Col, Typography } from 'antd';
import { orderService } from '../services/orderService';
import locale from 'antd/es/date-picker/locale/zh_CN';
import dayjs from 'dayjs';
import ReactECharts from 'echarts-for-react';

const { RangePicker } = DatePicker;
const { Title } = Typography;

const OrderList = ({ readOnly = false }) => {
  const [orders, setOrders] = useState([]);
  const [loading, setLoading] = useState(false);
  const [dateRange, setDateRange] = useState([]);
  const user = JSON.parse(localStorage.getItem('user'));
  const isAdmin = user?.permission === 'admin';

  const columns = [
    { title: '订单ID', dataIndex: 'id', key: 'id' },
    { title: '派单员', dataIndex: 'dispatch', key: 'dispatch' },
    { title: '接待员', dataIndex: 'receptionist', key: 'receptionist' },
    { title: '陪玩', dataIndex: 'companion', key: 'companion' },
    { title: '客户', dataIndex: 'customer', key: 'customer' },
    { title: '服务类型', dataIndex: 'serviceType', key: 'serviceType' },
    { title: '时长(分钟)', dataIndex: 'duration', key: 'duration' },
    { 
      title: '总金额', 
      dataIndex: 'totalPrice', 
      key: 'totalPrice',
      render: (value) => `¥${value?.toFixed(2) || '0.00'}`
    },
    { 
      title: '最终金额', 
      dataIndex: 'finalAmount', 
      key: 'finalAmount',
      render: (value) => `¥${value?.toFixed(2) || '0.00'}`
    },
    { 
      title: '创建时间', 
      dataIndex: 'createTime', 
      key: 'createTime',
      render: (value) => dayjs(value).format('YYYY-MM-DD HH:mm:ss')
    }
  ];

  const fetchOrders = useCallback(async () => {
    if (!dateRange || dateRange.length !== 2) return;

    setLoading(true);
    try {
      const [startDate, endDate] = dateRange;
      const data = await orderService.getOrdersByRange(
        startDate.format('YYYY-MM-DD'),
        endDate.format('YYYY-MM-DD')
      );
      
      // 如果不是管理员，只显示与用户相关的订单
      if (!isAdmin) {
        const filteredOrders = data.filter(order => 
          order.companion === user.username || 
          order.customer === user.username ||
          order.dispatch === user.username ||
          order.receptionist === user.username
        );
        setOrders(filteredOrders);
      } else {
        setOrders(data);
      }
    } catch (error) {
      message.error('获取订单数据失败');
    } finally {
      setLoading(false);
    }
  }, [dateRange, isAdmin, user?.username]);

  useEffect(() => {
    if (dateRange.length === 2) {
      fetchOrders();
    }
  }, [dateRange, fetchOrders]);

  const handleDateRangeChange = (dates) => {
    setDateRange(dates || []);
  };

  const getServiceTypeChartOption = () => {
    const serviceTypeStats = orders.reduce((acc, order) => {
      acc[order.serviceType] = (acc[order.serviceType] || 0) + 1;
      return acc;
    }, {});

    return {
      title: {
        text: '服务类型分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: Object.keys(serviceTypeStats)
      },
      series: [
        {
          name: '服务类型',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: Object.entries(serviceTypeStats).map(([name, value]) => ({
            name,
            value
          }))
        }
      ]
    };
  };

  const getAmountChartOption = () => {
    const amountStats = orders.reduce((acc, order) => {
      const range = Math.floor(order.totalPrice / 100) * 100;
      const key = `${range}-${range + 99}`;
      acc[key] = (acc[key] || 0) + 1;
      return acc;
    }, {});

    return {
      title: {
        text: '订单金额分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: Object.keys(amountStats)
      },
      series: [
        {
          name: '订单金额',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: Object.entries(amountStats).map(([name, value]) => ({
            name: `¥${name}`,
            value
          }))
        }
      ]
    };
  };

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        <Title level={2} style={{ marginBottom: 24 }}>
          {isAdmin ? '订单管理' : '我的订单'}
        </Title>
        <Space direction="vertical" style={{ width: '100%' }}>
          <div>
            <RangePicker
              onChange={handleDateRangeChange}
              locale={locale}
              style={{ width: 300 }}
              value={dateRange}
            />
          </div>
          
          {orders.length > 0 && (
            <Row gutter={16} style={{ marginTop: 16 }}>
              <Col span={12}>
                <Card>
                  <ReactECharts option={getServiceTypeChartOption()} style={{ height: 400 }} />
                </Card>
              </Col>
              <Col span={12}>
                <Card>
                  <ReactECharts option={getAmountChartOption()} style={{ height: 400 }} />
                </Card>
              </Col>
            </Row>
          )}

          <Table
            columns={columns}
            dataSource={orders}
            loading={loading}
            rowKey="id"
            scroll={{ x: true }}
          />
        </Space>
      </Card>
    </div>
  );
};

export default OrderList;